﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ninject;
using MKAdmin.DTO.Web.Common;
using MKAdmin.DTO.Web.Organization.PermissionSetting;
using MKAdmin.IService.Web.Organization;
using MKAdmin.Web.App_Start;
using MKAdmin.Web.Authorizes;
using MKAdmin.Web.Controllers;

namespace MKAdmin.Web.Areas.Organization.Controllers
{
    public class PermissionSettingController : BaseMvcController
    {
        [Inject]
        public IPermissionSettingService PermissionSettingService { set; get; }
        // GET: Organization/PermissionSetting
        public ActionResult Index()
        {
            return View(PageViewFilesConfig.BasicTableIndex);
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult List(GetPermissionListParameter parameter)
        {
            var userInfo = CurrentUser.GetLoginInfo();

            var result = PermissionSettingService.List(parameter, userInfo);

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AllotList(GetPermissionAllotListParameter parameter)
        {
            var userInfo = CurrentUser.GetLoginInfo();

            var result = PermissionSettingService.AllotList(parameter, userInfo);

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 权限新增
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddRole(RoleAddParameter parameter)
        {
            var info = CurrentUser.GetLoginInfo();
            var result = PermissionSettingService.AddRole(parameter, info);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 权限编辑
        /// </summary>
        /// <returns></returns>
        public JsonResult EditRole(RoleEditSaveParameter parameter)
        {
            var info = CurrentUser.GetLoginInfo();
            var result = PermissionSettingService.EditRole(parameter, info);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 权限删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteRole(RoleDelParameter parameter)
        {
            var info = CurrentUser.GetLoginInfo();
            var result = PermissionSettingService.DeleteRole(parameter, info);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 获取权限功能信息表
        /// </summary>
        /// <returns></returns>
        /*[HttpPost]
        public JsonResult GetPermissionInfo()
        {
            var permissions = PermissionSettingService.GetPermissionInfo(); //所有的
            var info = CurrentUser.GetLoginInfo();
            var nodesAll = new Result<List<TreeNode>>()
            {
                status = true,
                data = new List<TreeNode>()
            };
            foreach (var permission in permissions.data)
            {
                TreeNode node = new TreeNode();
                node.ID = permission.PermissionId;
                node.Name = permission.PermissionName;
                node.ParentID = permission.FPermissionId;
                //node.State = permission.State;
                nodesAll.data.Add(node);
            }
            if (info.TypeCode!=10)//要过滤
            {
                
            }
            else
            {
                nodesAll.data.Add(new TreeNode() { ID = "-1", Name = "所有权限", ParentID = "-2" });//所有的
                //return TreeNodeHelper.GetTreeJson("-2", nodesAll);
            }
            return Json(nodesAll, JsonRequestBehavior.DenyGet);
        }*/
        /// <summary>
        /// 获取权限功能信息表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetPermissionInfoTree()
        {
            var permissions = PermissionSettingService.GetPermissionInfo(); //所有的
            var info = CurrentUser.GetLoginInfo();
            var result = new Result<JArray>()
            {
                status = true,
                data = new JArray()
            };
            List<TreeNode> nodesAll = new List<TreeNode>();
            foreach (var permission in permissions.data)
            {
                TreeNode node = new TreeNode();
                node.ID = permission.PermissionId;
                node.Name = permission.PermissionName;
                node.ParentID = permission.FPermissionId;
                //node.State = permission.State;
                nodesAll.Add(node);
            }
            List<TreeNode> nodes = new List<TreeNode>();
            if (info.OperatorId != 1)//要过滤(只加载它自身权限下的节点，并非全部节点，账号所创建的角色权限不能大于其自身权限)
            {
                var permissionById = PermissionSettingService.GetPermissionInfoById(info.OperatorId);
                List<TreeNode> roleTreeNodes = new List<TreeNode>();
                foreach (var permission in permissionById)
                {
                    TreeNode node = new TreeNode();
                    node.ID = permission.RightId.ToString();
                    node.Name = permission.RightName;
                    node.ParentID = permission.RightParentId.ToString();
                    node.IconCls = permission.IconName;
                    node.Url = permission.Remark;
                    roleTreeNodes.Add(node);
                }
                nodes = nodesAll.Where(n => roleTreeNodes.Select(u => u.ID).Contains(n.ID)).ToList();
                result.data = GetTreeJson("-1", nodes);
                return JsonConvert.SerializeObject(result);
            }
            else
            {
                //nodesAll.Add(new TreeNode() { ID = "-1", Name = "所有权限", ParentID = "-2" });//所有的
                //result.data=GetTreeJson("-2", nodesAll);
                result.data = GetTreeJson("-1", nodesAll);
                return JsonConvert.SerializeObject(result);
            }
        }
        private JArray GetTreeJson(string rootId, List<TreeNode> nodes)
        {
            JArray jArray = new JArray();

            TreeNode rootNode = nodes.Find(n => n.ID == rootId);
            if (rootNode != null)
            {
                JObject root = new JObject
                {
                    {"id", rootNode.ID.ToString()},
                    {"text", rootNode.Name},
                 /*   {"state",rootNode.State},
                    {"iconCls",rootNode.IconCls},
                    {"url",rootNode.Url},*/
                };
                root.Add("children", GetChildArray(rootId, nodes));
                jArray.Add(root);
            }
            else
            {
                jArray = GetChildArray(rootId, nodes);
            }

            return jArray;
        }

        private JArray GetChildArray(string parentID, IEnumerable<TreeNode> nodes)
        {
            JArray childArray = new JArray();

            foreach (var node in nodes.Where(x => x.ParentID == parentID))
            {
                JObject subObject = new JObject
                {
                    {"id", node.ID.ToString()},
                    {"text", node.Name},
                    /*{"state",node.State},
                    {"iconCls",node.IconCls},
                    {"url",node.Url},*/
                };

                if (node.Checked.HasValue)
                {
                    subObject.Add("checked", node.Checked.Value);
                }

                if (nodes.Where(y => y.ParentID == node.ID).Any())
                {
                    subObject.Add("children", GetChildArray(node.ID, nodes));
                }
                childArray.Add(subObject);
            }

            return childArray;
        }

        #region 根据权限ID获取角色权限
        /// <summary>
        /// 根据权限ID获取角色权限
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public JsonResult GetRoleRightByRoleId(RoleEditParameter parameter)
        {
            var result = PermissionSettingService.GetRoleRightByRoleId(parameter);
            return Json(result, JsonRequestBehavior.DenyGet);
        }
        #endregion

        /// <summary>
        /// 获取用户菜单权限信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public JsonResult PermissionMenuList()
        {
            var userInfo = CurrentUser.GetLoginInfo();
            var result = PermissionSettingService.PermissionMenuList(userInfo);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 获取用户功能权限信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public JsonResult PermissionFunctionList(GetPermissionDataListParameter parameter)
        {
            var userInfo = CurrentUser.GetLoginInfo();
            var result = PermissionSettingService.PermissionFunctionList(parameter.rightId, userInfo);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

    }
}